package veetouch.contact;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import veetouch.syncpc.R;
import veetouch.syncpc.VtAndroidSyncActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.Intents.Insert;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ContactActivity extends Activity
{
	//////////////////////////////////////////////////////////
	//
	// DIALOG ID
	//
	//////////////////////////////////////////////////////////
	public static final int DIALOG_CONFIRM_SHARE	= 0;	// Display confirm dialog
	
	public AlertDialog dialog; 			// Popup dialog
	public static final int PICK_CONTACT    = 1;
	
	private String contactName = "";
	private byte[] vCardByte;
	
	 
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.contact);
        
        // Set default button
        Button button_home = (Button) findViewById(R.id.Button_home);
        button_home.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View arg0) 
			{
				onBackPressed();
			}
		});
        selectContactFromContactList();
    }
    
    private void selectContactFromContactList()
    {
    	Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent,PICK_CONTACT);
    }
    
    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) 
    {
    	super.onActivityResult(reqCode, resultCode, data);
    	 switch (reqCode) {
    	 	case (PICK_CONTACT):
    	 		if (resultCode == Activity.RESULT_OK) 
    	 		{
    	 			/*Normal Contact object
    	 			Uri contactData = data.getData();
    	 			Cursor cursor =  managedQuery(contactData, null, null, null, null);
    	 			cursor.moveToNext();
    	 			String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
    	 	        String name      = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
    	 			*/
    	 			
    	 			// VCard Contact Object
    	 			Uri contactData = data.getData();
    	 			Cursor cursor =  managedQuery(contactData, null, null, null, null);
    	 			cursor.moveToNext();
    	 			String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    	 			Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI,lookupKey); 
    	 			AssetFileDescriptor fd;
					try 
					{
						fd = getContentResolver().openAssetFileDescriptor(uri, "r");
						FileInputStream fis = fd.createInputStream();
						byte[] buf = new byte[(int)fd.getDeclaredLength()]; 
                        if (0 < fis.read(buf)) 
                        { 
                	 		fis.close();
                        	this.contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
                	 		
                	 		// Data vCard
                	 		this.vCardByte = buf;
                	 		//String vCard = new String(buf);
                	 		showDialog(ContactActivity.DIALOG_CONFIRM_SHARE);
                        }
					} 
					catch (FileNotFoundException e) {} 
					catch (IOException e) {}
    	 		}
    	 		break;
    	 }
    }
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) 
	{
		Builder builder;
		switch (id) {
		 	// Only text
			case ContactActivity.DIALOG_CONFIRM_SHARE:
				builder = new AlertDialog.Builder(this);
				builder.setMessage("Please confirm share contact: \n"+contactName);
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
				{
	                public void onClick(DialogInterface dialog, int which) 
	                {
	                	// Back press
	                	onBackPressed();
	                	
	                	// Start sync
	                	Intent intent = new Intent(getApplicationContext(),VtAndroidSyncActivity.class);
						intent.putExtra("SYNC_TYPE",VtAndroidSyncActivity.SYNC_TYPE_UPLOAD_CONTACT);
						byte[] datas = vCardByte;
						intent.putExtra("DATA",datas);
						startActivity(intent);
	                }
	            });
				// Cancel and back to home
				builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                	// Back press
	                	onBackPressed();
	                }
	            });
				dialog = builder.create();
	            dialog.show();
			break;
		}
		return null;
	}
}
